package bktech.soict.hust.bknote.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import bktech.soict.hust.bknote.R;
import bktech.soict.hust.bknote.activity.sms.Sound;
import bktech.soict.hust.bknote.util.Key;
import bktech.soict.hust.bknote.util.MyPreferenceII;
import bktech.soict.hust.bknote.util.MyToast;

public class SmsReceive extends BroadcastReceiver {

	// phone number of message
	private String phone = "";
	private Sound ambaohoc;
	// body of message
	private String content = "";
	private String smsvip[]={"hoc","yeu","thi"};
	// preference used to get data
	private MyPreferenceII preference;

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		SmsMessage[] messages = null;
		preference = MyPreferenceII.getInstance(context);

		if (bundle != null) {

			// Get received SMS array
			Object[] pdus = (Object[]) bundle.get("pdus");

			// Initialization array SmsMessage with length equal length of array
			// received SMS
			messages = new SmsMessage[pdus.length];

			for (int i = 0; i < messages.length; i++) {
				// create SmsMessage object from received SMS
				messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);

				// after create SmsMessage, we could get content and address of
				// SMS
				content = messages[i].getMessageBody();

				// get address
				phone = messages[i].getOriginatingAddress();

				for (int i1=0;i1<smsvip.length;i1++)
				if (timkiemSMS(content, smsvip[i1])){
					ambaohoc=new Sound(context, R.raw.sms);
						MyToast.show(context, "PhoneNumber: " + phone
								+ " sent message: " + content);
						ambaohoc.play();
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						ambaohoc.stop();
					break;
				}
			}
		}

		// When we aborted broadcast, we call method abortBroadcast() to
		// abort message
		if (preference.getBoolean(Key.ABORT_MESSAGE, false)) {

			// Method used to abort message, then received message not be put to
			// inbox message
			abortBroadcast();
			
			MyToast.show(context, "Abort message");
		}
	}
	public boolean timkiemSMS(String s,String s1){//tim kiem xau s1 trong s
		int n=s.length();
		int m=s1.length(),j;
		char ss,ss1;
		if (m>n) return false;
		for (int i=0;i<=n-m;i++){
			for (j=0;j<m;j++){
				ss=s.charAt(i+j);
				ss1=s1.charAt(j);
				if (ss!=ss1) break;	
				if (j==m-1) return true;
			}
		}
		return false;
	}
}
